package com.wryyyyy.controller;

import com.wryyyyy.dto.LoginFormDTO;
import com.wryyyyy.dto.Result;
import com.wryyyyy.dto.UserDTO;
import com.wryyyyy.service.IUserService;
import com.wryyyyy.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wryyyyy
 * @since 2024-05-14
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone, HttpSession session) {
        // 发送短信验证码并保存验证码
        return userService.sendCode(phone,session);
    }

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        //实现登录功能
        return userService.login(loginForm,session);
    }

    /**
     * 设置密码
     */
    @PutMapping("/setPassword")
    public Result setPassword(@RequestParam("password") String password) {
        UserDTO user = UserHolder.getUser();
        return userService.setPassword(user.getId(), password);
    }

    /**
     * 密码登录
     */
    @PostMapping("/loginPwd")
    public Result loginPwd(@RequestBody LoginFormDTO loginForm, HttpSession session) {
        //实现登录功能
        return userService.loginPwd(loginForm,session);
    }

    /**
     * 获取当前登录的用户
     * @return 用户dto
     */
    @GetMapping("/me")
    public Result me() {
        //获取当前登录的用户并返回
        UserDTO user = UserHolder.getUser();//拦截器已经把对象放在UserHolder里面了
        if (user != null) {
            return Result.ok(userService.getById(user.getId()));
        }
        else {
            return Result.fail("用户未登录");
        }
    }
}